package com.zg.scf.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zg.common.core.R;
import com.zg.common.core.exception.BusinessException;
import com.zg.common.core.util.RedisUtil;
import com.zg.message.api.domain.req.MsgInfoAddReq;
import com.zg.scf.feign.MsgInfoFeign;
import com.zg.scf.constant.ScfConstant;
import com.zg.scf.domain.req.ScfSmsValidCodeReq;
import com.zg.scf.service.ScfSmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScfSmsServiceImpl implements ScfSmsService {

    private final MsgInfoFeign msgInfoApi;
    private final RedisUtil redisUtil;
    private static final int CODE_EXPIRE_SECONDS = 300;
    private static final int SEND_EXPIRE_SECONDS = 60;
    private static final Long CODE_TEMPLATE_ID = 1L;

    @Override
    public void sendCode(String phone) {
        String key = ScfConstant.SMS_CODE_KEY + phone;
        long expire = redisUtil.getExpire(key);
        if ((CODE_EXPIRE_SECONDS - expire) < 60) {
            BusinessException.happen(SEND_EXPIRE_SECONDS + "秒内不能重复发送");
        }
        String code = RandomStringUtils.randomNumeric(6);

        // 发送短信
        MsgInfoAddReq addReq = new MsgInfoAddReq();
        addReq.setTitle("验证码");
        addReq.setContent(code);
        addReq.setTemplateId(CODE_TEMPLATE_ID);
        addReq.setSender("system");
        addReq.setSendTime(DateUtil.date());
        addReq.setReceiverAdd(phone);
        R sendResult = msgInfoApi.add(addReq);
        if (sendResult.isOk()) {
            redisUtil.set(key, code, CODE_EXPIRE_SECONDS);
        } else {
            BusinessException.happen("验证码发送失败");
        }
    }

    @Override
    public void validCode(ScfSmsValidCodeReq req) {
        String key = ScfConstant.SMS_CODE_KEY + req.getPhone();
        String code = redisUtil.get(key);
        if (!Objects.equals(code, req.getCode())) {
            BusinessException.happen("验证码错误");
        }
    }
}
